import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: null,
    isLoggedIn: false,
  }),

  actions: {
    setToken(token) {
      this.token = token
      uni.setStorageSync('token', token)
    },

    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = true
      uni.setStorageSync('userInfo', userInfo)
    },

    logout() {
      this.token = ''
      this.userInfo = null
      this.isLoggedIn = false
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
    },

    initFromStorage() {
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('userInfo')
      if (token && userInfo) {
        this.token = token
        this.userInfo = userInfo
        this.isLoggedIn = true
      }
    },

    isUserLoggedIn() {
      return this.isLoggedIn
    },
  },
})
